﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace NotifierService.Service
{
    public class RealtimeBroadcastServiceV4 : SingletonBase<RealtimeBroadcastServiceV4>, IDisposable
    {
        public class IPv4NotSupportException : ApplicationException
        {
            public IPv4NotSupportException() : base("IPv6 is not supported on this OS.") { }
        }

        #region Fields

        private Dictionary<IPAddress, ServiceBase> _ipAddrServiceInstDic = new Dictionary<IPAddress, ServiceBase>();
        private UdpClient _listenSocket;
        private volatile bool _isRunning = false;
        private readonly object _syncLocker = new object();
        private Thread _socketThread;
        private bool _readyToQuit = false;

        #endregion

        #region Constructor&Destructor

        public RealtimeBroadcastServiceV4()
        {
        }

        ~RealtimeBroadcastServiceV4()
        {
            Dispose(false);
        }

        #endregion

        #region Properties

        public bool IsRunning { get { return _isRunning; } }
        public bool Enabled { get { return Socket.OSSupportsIPv4; } }

        #endregion

        #region Public Methods

        public void Start()
        {
            if (_isRunning)
                throw new InvalidOperationException("Service is already running.");

            if (!Socket.OSSupportsIPv4)
            {
                Console.WriteLine(">>>Realtime broadcast(ipv4) service is not supported.");
                throw new IPv4NotSupportException();
            }

            _isRunning = true;

            //ygjkhghjgvgguygvyukjg
            _listenSocket = new UdpClient(2200, AddressFamily.InterNetwork);
            //TODO: IPv6 Support.

            //_listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            _socketThread = new Thread(PrivateSocketProc);
            _socketThread.IsBackground = true;
            _socketThread.Start();

            Console.WriteLine(">>>Realtime broadcast(ipv4) service started at 0.0.0.0:2200.");
        }

        public void Stop()
        {
            _readyToQuit = true;
        }

        public void AddService(ServiceBase service)
        {
            Monitor.Enter(_syncLocker);

            if (_ipAddrServiceInstDic.ContainsKey(service.GetIPAddress())) return;

            if (service.GetClientEndpoint().AddressFamily == AddressFamily.InterNetwork)
                _ipAddrServiceInstDic.Add(service.GetIPAddress(), service);
            Monitor.Exit(_syncLocker);
        }

        public void RemoveService(ServiceBase service)
        {
            Monitor.Enter(_syncLocker);

            if (!_ipAddrServiceInstDic.ContainsKey(service.GetIPAddress())) return;

            _ipAddrServiceInstDic.Remove(service.GetIPAddress());

            Monitor.Exit(_syncLocker);
        }

        #endregion

        #region Private Mehtods

        private void PrivateSocketProc(object state)
        {
            try
            {
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0); ;
                byte[] buffer = new byte[1024 * 512];
                ServiceBase service;

                while (_isRunning&&(!_readyToQuit))
                {
                    buffer = _listenSocket.Receive(ref endPoint);
                    var addr = (endPoint as IPEndPoint).Address;

                    Monitor.Enter(_syncLocker);
                    if (!_ipAddrServiceInstDic.TryGetValue(addr, out service))
                    {
                        Monitor.Exit(_syncLocker);
                        continue;
                    }

                    service.InternalProcessVoiceBuffer(buffer, buffer.Length);

                    Monitor.Exit(_syncLocker);
                }

                foreach(var s in _ipAddrServiceInstDic.Values)
                {
                    s.InternalBroadcastStopped();
                }

            }
            catch (SocketException)
            {
                foreach (var s in _ipAddrServiceInstDic.Values)
                {
                    s.InternalBroadcastStopped();
                }
                _isRunning = false;
            }
            catch (Exception)
            {
                foreach (var s in _ipAddrServiceInstDic.Values)
                {
                    s.InternalBroadcastStopped();
                }
                _isRunning = false;
            }
        }

        #endregion

        #region IDisposable Impl

        private bool _isDisposed = false;

        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                if (disposing)
                {
                }

                //release any unmanaged resource.
                GC.SuppressFinalize(this);
            }

            _isDisposed = true;
        }
        #endregion
    }
}
